<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>001深浅拷贝</title>
</head>
<body>
    <script>
        // 拷贝是针对引用数据类型，而且一般以数组 和 对象为主
        function shallowClone(source) {
            if(typeof source !== 'object' || source == null) {
                return source
            }
            let target = Array.isArray(source) ? [] : {}
            for(let key in source) {
                target[key] = source[key]
            }
            return target
        }

        let easyObj = {
            name: 'lqj',
            age: 18,
            hobby: [1,2,3]
        }
        let shallowCloneEasyObj = shallowClone(easyObj)
        easyObj.name = 'tjc'
        easyObj.hobby[0] = '123'
        console.log('easyObj', easyObj)
        console.log('shallowCloneEasyObj', shallowCloneEasyObj)

        // 深拷贝
        function deepClone(source) {
            if(typeof source !== 'object' || source == null) {
                return source
            }
            let target = Array.isArray(source) ? [] : {}
            for(let key in source) {
                target[key] = deepClone(source[key])
            }
            return target
        }
        let complexObj = {
            name: 'lqj',
            age: 18,
            friend: {
                name: 'tjc',
                age: 19,
                hobby: [1,2,3]
            }
        }
        let deepCloneComplexObj = deepClone(complexObj)
        complexObj.name = 'sq'
        complexObj.friend.name = 'jz'
        complexObj.friend.hobby[0] = '123'
        console.log('complexObj', complexObj)
        console.log('deepCloneComplexObj', deepCloneComplexObj)
    </script>
</body>
</html>